/**
 * Created by lenovo on 2017/7/20.
 */
let config = require('../../config');
let dayu = require('alidayu-node');
let captchapng = require('captchapng');

let redisTool = require('../../common/utils/redistools.js');
let SMS = new dayu(config.sms.appkey, config.sms.appsecret);
let WXMember = require('./WXMemberController');

module.exports = {
    showActivation: function (req, res) {
        res.render('wx-activation',{
            title:'修改绑定手机',
            success:false
        })
    },
    showRegister: function (req, res) {
        res.render('wx-register',{
            title:'注册会员',
        })
    },
    getGraphicCode: function (req, res) {
        if (!req.signedCookies.userinfo || !req.signedCookies.userinfo.openid){
            res.json({
                errorMessage: 'openid无法获取！'
            });
        } else {
            let open_id = req.signedCookies.userinfo.openid;

            let width = 80;
            let height = 40;
            let code = Math.random().toString().substring(2, 6);
            let key = 'pic-' + open_id;
            redisTool.set(key, code, 600, function (err, result) {
                if (err) {
                    console.log('图片验证码缓存失败')
                } else {
                    console.log('图片验证码缓存成功')
                }
            });
            let p = new captchapng(width, height, code);
            p.color(255, 255, 255, 255);
            p.color(80, 80, 80, 255);

            let img = p.getBase64();
            let imgbase64 = new Buffer(img, 'base64');
            res.writeHead(200, {
                'Content-Type': 'image/png'
            });
            res.end(imgbase64);
        }
    },

    getIdentifyingCode: function (req, res) {
        if (!req.signedCookies.userinfo || !req.signedCookies.userinfo.openid){
            res.json({
                errorMessage: 'openid无法获取！'
            });
            return;
        }
        let openId = req.signedCookies.userinfo.openid;
        let graphicCode = req.body.graphiccode;
        let phoneNumber = req.body.phonenumber;

        if (!graphicCode) {
            res.json({
                errorMessage: '请输入正确的图形验证码！'
            });
            return;
        }
        if (!phoneNumber) {
            res.json({
                errorMessage: '请输入有效的手机号码！'
            });
            return;
        }

        let graphicKey = 'pic-' + openId;
        redisTool.get(graphicKey, function (err, result) {
            console.log('error: ' + err);
            console.log('result: ' + result);
            if (err) {
                res.json({
                    errorMessage: '图片验证码验证失败！'
                });
            } else if (result != graphicCode) {
                res.json({
                    errorMessage: '请输入正确的验证码！'
                });
            } else {
                let smsCode = Math.random().toString().substring(2, 6);

                let date = new Date();
                let datetime = date.getTime();
                date.setMinutes(date.getMinutes() + 10);
                let endtime = date.getTime();

                redisTool.setHset(phoneNumber, {
                    phone: phoneNumber,
                    createtime: datetime,
                    expiretime: endtime,
                    smscode: smsCode,
                    username: ''
                }, function (err, result) {
                    console.log('error-set: ' + err);
                    console.log('result-set: ' + result);
                    if (err) {
                        res.json({
                            errorMessage: err
                        });
                    } else {
                        SMS.smsSend({
                            sms_free_sign_name: '百视通点播影院',
                            sms_param: JSON.stringify({"number": '' + smsCode}),
                            rec_num: phoneNumber,
                            sms_template_code: 'SMS_56765019'
                        }, function (response) {
                            console.log('response: ' + response);
                            res.json(response);
                        })
                    }
                });

            }
        });
    },

    activation: function (req, res) {
        if (!req.signedCookies.userinfo || !req.signedCookies.userinfo.openid){
            res.json({
                errorMessage: 'openid无法获取！'
            });
            return;
        }

        let identifyingcode = req.body.identifyingcode;
        let phoneNumber = req.body.phonenumber;

        if (!identifyingcode) {
            res.json({
                errorMessage: '请输入正确的短信验证码！'
            });
            return;
        }
        if (!phoneNumber) {
            res.json({
                errorMessage: '请输入有效的手机号码！'
            });
            return;
        }
        redisTool.getHgetall(phoneNumber, function (err, data) {
            console.log(data);
            if (err) {
                res.json({
                    errorMessage: err
                });
            } else if (!data || data.smscode != identifyingcode) {
                res.json({
                    errorMessage: '短信验证码错误！'
                });
            } else {
                WXMember.setMemberInformation(req,res,function (err, code, result) {
                    if (code) {
                        res.json({
                            errorMessage:err
                        });
                    } else {
                        res.json(result);
                    }
                });
            }
        });

    },

    activationSuccess: function (req, res) {
        res.render('wx-activation-success',{
            title:'激活成功！'
        });
    }
};
